package com.opages.netty.demo.netty.rpc.common;

import com.opages.netty.demo.netty.stickybag.MessageProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author daizhong.liu
 * @create 2021-12-15 15:09
 **/
public class MessageEncoder extends MessageToByteEncoder<RpcProtocol> {
    private int count;
    @Override
    protected void encode(ChannelHandlerContext ctx, RpcProtocol msg, ByteBuf out) throws Exception {
        System.err.println("MessageEncoder调用");
        int[] protocolLen = msg.getProtocolLen();
        out.writeInt(protocolLen[0]);
        out.writeInt(protocolLen[1]);
        out.writeInt(protocolLen[2]);
        out.writeInt(protocolLen[3]);
        out.writeInt(protocolLen[4]);
        out.writeBytes(msg.getHeader());
        out.writeBytes(msg.getClassName());
        out.writeBytes(msg.getMethodName());
        out.writeBytes(msg.getParams());
        if(msg.getResult() != null) {
            out.writeBytes(msg.getResult());
        }
        System.err.println(ctx.channel().localAddress()+"调用次数:"+(++count));
    }
}
